package com.ruoyi.common.utils.poster;

import com.ruoyi.common.exception.CustomException;
import sun.font.FontDesignMetrics;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class PosterUtil {

    static Poster initPoster(Poster poster_) {
        return initPoster(poster_.getWidth(),poster_.getHeight(),poster_.getQrCodeUrl());
    }


    static Poster initPoster(int width,int height,String qrCodeUrl) {
        Poster poster = new Poster();
        //画布
        poster.setWidth(width);
        poster.setHeight(height);

        //小程序码
        poster.setQrCodeUrl(qrCodeUrl);
        poster.setQrCodeWidth(175);
        poster.setQrCodeHeight(175);
        poster.setQrCodeX((int) (width / 18));
        poster.setQrCodeY(height - poster.getQrCodeHeight() - 30);
//        Font font = getFont();
//        //tips1
//        poster.setTip1("客服电话：400-0371-298");
//        poster.setTip1Color(Color.BLACK);
////        poster.setTip1Font(new Font("宋体", Font.BOLD, width / 21));
//        poster.setTip1Font(font);
//        poster.setTip1X(poster.getQrCodeX() + poster.getQrCodeWidth() + 30);
//        poster.setTip1Y(poster.getQrCodeY() + 40);
//        //tips2
//        poster.setTip2("微信搜索小程序\"代驾审车\"");
//        poster.setTip2Color(Color.BLACK);
//        poster.setTip2Font(font);
//        poster.setTip2X(poster.getQrCodeX() + poster.getQrCodeWidth() + 30);
//        poster.setTip2Y(poster.getQrCodeY() + 90);
//        //tips3
//        poster.setTip3("快来体验吧!");
//        poster.setTip3Color(Color.BLACK);
//        poster.setTip3Font(font);
//        poster.setTip3X(poster.getQrCodeX() + poster.getQrCodeWidth() + 30);
//        poster.setTip3Y(poster.getQrCodeY() + 140);
        return poster;
    }

    public static void drawPoster(Poster poster) throws Exception {
        long startTime = System.currentTimeMillis();
        String qrCodeUrl = poster.getQrCodeUrl();
        BufferedImage qrCodeImage = ImageIO.read(new URL(qrCodeUrl));
        int width = poster.getWidth();
        int height = poster.getHeight();
        //画布
        BufferedImage canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) canvas.getGraphics();
        //设置背景色
        g.setBackground(Color.WHITE);
        g.clearRect(0, 0, width, height);
        // 画背景图
        InputStream bgStream = PosterUtil.class.getClassLoader().getResourceAsStream("poster.png");
        BufferedImage bgImage = ImageIO.read(bgStream);
        g.drawImage(bgImage.getScaledInstance(poster.getWidth(), poster.getHeight(), Image.SCALE_SMOOTH),0, 0, null);
        //画小程序码
        g.drawImage(qrCodeImage.getScaledInstance(poster.getQrCodeWidth(), poster.getQrCodeHeight(), Image.SCALE_SMOOTH),
                poster.getQrCodeX(), poster.getQrCodeY(), null);
        //画tips1
        g.setColor(poster.getTip1Color());
        g.setFont(poster.getTip1Font());
        g.drawString(poster.getTip1(), poster.getTip1X(), poster.getTip1Y());
        //画tips2
        g.setColor(poster.getTip2Color());
        g.setFont(poster.getTip2Font());
        g.drawString(poster.getTip2(), poster.getTip2X(), poster.getTip2Y());

        //画tips3
        g.setColor(poster.getTip3Color());
        g.setFont(poster.getTip3Font());
        g.drawString(poster.getTip3(), poster.getTip3X(), poster.getTip3Y());
        //画底部栏
        g.setColor(poster.getFooterColor());
        g.fillRect(poster.getFooterX(), poster.getFooterY(), poster.getFooterWidth(), poster.getFooterHeight());
        g.dispose();
        File resultImg = new File("D:\\demo.png");
        ImageIO.write(canvas, "png", resultImg);
        //上传服务器代码
        //ByteArrayOutputStream bs = new ByteArrayOutputStream();
        //ImageOutputStream imgOut = ImageIO.createImageOutputStream(bs);
        //ImageIO.write(canvas, "png", imgOut);
        //InputStream inSteam = new ByteArrayInputStream(bs.toByteArray());
        //String url = OSSFactory.build().upload(inSteam, UUID.randomUUID().toString()+".png");
        System.out.println("生成成功！");
        System.out.println("耗时: " + (System.currentTimeMillis() - startTime) / 1000.0 + "s");
        System.out.println("生成文件路径: " + resultImg.getAbsolutePath());
    }



    public static BufferedImage drawPoster(InputStream qrInputStream) throws Exception {
        Poster poster = initPoster(750,1334,null);
        // 画背景图
        InputStream bgStream = PosterUtil.class.getClassLoader().getResourceAsStream("poster2x.png");
        BufferedImage bgImage = ImageIO.read(bgStream);
        Graphics2D g = bgImage.createGraphics();
        //画小程序码
        BufferedImage qrCodeImage = ImageIO.read(qrInputStream);
//        BufferedImage qrCodeImage = ImageIO.read(new File("D:\\qr.jpg"));
        g.drawImage(qrCodeImage.getScaledInstance(poster.getQrCodeWidth(), poster.getQrCodeHeight(), Image.SCALE_SMOOTH),
                poster.getQrCodeX(), poster.getQrCodeY(), null);
//        //画tips1
//        g.setColor(poster.getTip1Color());
//        g.setFont(poster.getTip1Font());
//        g.drawString(poster.getTip1(), poster.getTip1X(), poster.getTip1Y());
//        //画tips2
//        g.setColor(poster.getTip2Color());
//        g.setFont(poster.getTip2Font());
//        g.drawString(poster.getTip2(), poster.getTip2X(), poster.getTip2Y());
//        //画tips3
//        g.setColor(poster.getTip3Color());
//        g.setFont(poster.getTip3Font());
//        g.drawString(poster.getTip3(), poster.getTip3X(), poster.getTip3Y());
        //画底部栏
        g.setColor(poster.getFooterColor());
        g.fillRect(poster.getFooterX(), poster.getFooterY(), poster.getFooterWidth(), poster.getFooterHeight());
        g.dispose();
        return bgImage;
    }



    private static BufferedImage circle(String avatar_img, int width) throws Exception {
        BufferedImage avatar = ImageIO.read(new URL(avatar_img));
        BufferedImage newAvatar = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, width, width);
        Graphics2D g2 = newAvatar.createGraphics();
        newAvatar = g2.getDeviceConfiguration().createCompatibleImage(width, width, Transparency.TRANSLUCENT);
        g2 = newAvatar.createGraphics();
        g2.setComposite(AlphaComposite.Clear);
        g2.fill(new Rectangle(newAvatar.getWidth(), newAvatar.getHeight()));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2 = newAvatar.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.fillRoundRect(0, 0, width, width, width, width);
        g2.setComposite(AlphaComposite.SrcIn);
        g2.drawImage(avatar, 0, 0, width, width, null);
        g2.dispose();
        return newAvatar;
    }

    //文本换行处理
    public static String makeLineFeed(String zh, FontDesignMetrics metrics, int max_width) {
        StringBuilder sb = new StringBuilder();
        int line_width = 0;
        for (int i = 0; i < zh.length(); i++) {
            char c = zh.charAt(i);
            sb.append(c);
            // 如果主动换行则跳过
            if (sb.toString().endsWith("\n")) {
                line_width = 0;
                continue;
            }
            // FontDesignMetrics 的 charWidth() 方法可以计算字符的宽度
            int char_width = metrics.charWidth(c);
            line_width += char_width;
            // 如果当前字符的宽度加上之前字符串的已有宽度超出了海报的最大宽度，则换行
            if (line_width >= max_width - char_width) {
                line_width = 0;
                sb.append("\n");
            }
        }
        return sb.toString();
    }

    public static Font getFont(){
        Font font = null;
        InputStream bgStream = PosterUtil.class.getClassLoader().getResourceAsStream("simsun.ttc");
        try {
            Font temfont = Font.createFont(Font.TRUETYPE_FONT,bgStream);
            font = temfont.deriveFont(30F ).deriveFont(Font.BOLD);
        } catch (Exception e) {
            throw new CustomException("生成海报异常");
        }
        return font;
    }


    public static void main(String[] args) throws Exception {
        //二维码
        InputStream stream = null;
        BufferedImage bufferedImage = drawPoster(stream);

        File resultImg = new File("D:\\demo.png");
        ImageIO.write(bufferedImage, "png", resultImg);
    }
}